package sigar;

import java.net.InetAddress;

import org.hyperic.sigar.CpuInfo;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.FileSystem;
import org.hyperic.sigar.FileSystemUsage;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.NetFlags;
import org.hyperic.sigar.NetInterfaceConfig;
import org.hyperic.sigar.NetInterfaceStat;
import org.hyperic.sigar.OperatingSystem;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarNotImplementedException;
import org.hyperic.sigar.Swap;
import org.hyperic.sigar.Who;

public class Test {

	// CPU数量（单位：个）
	private void getSystemInfo() {
		Sigar sigar = new Sigar();
		try {
			// CPU数量
			System.out.println("CPU数量=" + sigar.getCpuInfoList().length);
			// CPU的相关信息
			CpuInfo infos[] = sigar.getCpuInfoList();
			for (int i = 0; i < infos.length; i++) {// 不管是单块CPU还是多CPU都适用
				CpuInfo info = infos[i];
				System.out.println("CPU的总量MHz=" + info.getMhz());
				System.out.println("CPU vendor=" + info.getVendor());
				System.out.println("CPU model=" + info.getModel());
				System.out.println("CPU cache size=" + info.getCacheSize());
			}
			// CPU的用户使用量、系统使用剩余量、总的剩余量、总的使用占用量等（单位：100%）
//			CpuPerc cpu = sigar.getCpuPerc();// 方式一，主要是针对一块CPU的情况
//			printCpuPerc(cpu);
			CpuPerc cpuList[] = sigar.getCpuPercList();// 方式二，不管是单块CPU还是多CPU都适用
			for (int i = 0; i < cpuList.length; i++) {
				printCpuPerc(cpuList[i]);
			}
			// 物理内存信息
			Mem mem = sigar.getMem();
			System.out.println("内存总量 = " + mem.getTotal() / 1024L + "K av");
			System.out.println("当前内存使用量 = " + mem.getUsed() / 1024L + "K used");
			System.out.println("当前内存剩余量 = " + mem.getFree() / 1024L + "K free");
			// 系统页面文件交换区信息
			Swap swap = sigar.getSwap();
			System.out.println("交换区总量 = " + swap.getTotal() / 1024L + "K av");
			System.out.println("当前交换区使用量 = " + swap.getUsed() / 1024L + "K used");
			System.out.println("当前交换区剩余量 = " + swap.getFree() / 1024L + "K free");
			// 取到当前操作系统的名称
			String hostname = "";
			try {
				hostname = InetAddress.getLocalHost().getHostName();
			} catch (Exception exc) {
				try {
					hostname = sigar.getNetInfo().getHostName();
				} catch (SigarException e) {
					hostname = "localhost.unknown";
				}
			}
			System.out.println(hostname);
			// 取当前操作系统的信息
			OperatingSystem OS = OperatingSystem.getInstance();
			// 操作系统内核类型如： 386、486、586等x86
			System.out.println("OS.getArch() = " + OS.getArch());
			System.out.println("OS.getCpuEndian() = " + OS.getCpuEndian());//
			System.out.println("OS.getDataModel() = " + OS.getDataModel());//
			// 系统描述
			System.out.println("OS.getDescription() = " + OS.getDescription());
			System.out.println("OS.getMachine() = " + OS.getMachine());//
			// 操作系统类型
			System.out.println("OS.getName() = " + OS.getName());
			System.out.println("OS.getPatchLevel() = " + OS.getPatchLevel());//
			// 操作系统的卖主
			System.out.println("OS.getVendor() = " + OS.getVendor());
			// 卖主名称
			System.out.println("OS.getVendorCodeName() = " + OS.getVendorCodeName());
			// 操作系统名称
			System.out.println("OS.getVendorName() = " + OS.getVendorName());
			// 操作系统卖主类型
			System.out.println("OS.getVendorVersion() = " + OS.getVendorVersion());
			// 操作系统的版本号
			System.out.println("OS.getVersion() = " + OS.getVersion());
			// 取当前系统进程表中的用户信息
			Who who[] = sigar.getWhoList();
			if (who != null && who.length > 0) {
				for (int i = 0; i < who.length; i++) {
					System.out.println("\n~~~~~~~~~" + String.valueOf(i) + "~~~~~~~~~");
					Who _who = who[i];
					System.out.println("getDevice() = " + _who.getDevice());
					System.out.println("getHost() = " + _who.getHost());
					System.out.println("getTime() = " + _who.getTime());
					// 当前系统进程表中的用户名
					System.out.println("getUser() = " + _who.getUser());
				}
			}
			// 取硬盘已有的分区及其详细信息
			FileSystem fslist[] = sigar.getFileSystemList();
			String dir = System.getProperty("user.home");// 当前用户文件夹路径
			for (int i = 0; i < fslist.length; i++) {
				System.out.println("\n~~~~~~~~~~" + i + "~~~~~~~~~~");
				FileSystem fs = fslist[i];
				// 分区的盘符名称
				System.out.println("fs.getDevName() = " + fs.getDevName());
				// 分区的盘符名称
				System.out.println("fs.getDirName() = " + fs.getDirName());
				System.out.println("fs.getFlags() = " + fs.getFlags());//
				// 文件系统类型，比如 FAT32、NTFS
				System.out.println("fs.getSysTypeName() = " + fs.getSysTypeName());
				// 文件系统类型名，比如本地硬盘、光驱、网络文件系统等
				System.out.println("fs.getTypeName() = " + fs.getTypeName());
				// 文件系统类型
				System.out.println("fs.getType() = " + fs.getType());
				FileSystemUsage usage = null;
				try {
					usage = sigar.getFileSystemUsage(fs.getDirName());
				} catch (SigarException e) {
					if (fs.getType() == 2)
						throw e;
					continue;
				}
				switch (fs.getType()) {
				case 0: // TYPE_UNKNOWN ：未知
					break;
				case 1: // TYPE_NONE
					break;
				case 2: // TYPE_LOCAL_DISK : 本地硬盘
					// 文件系统总大小
					System.out.println(" Total = " + usage.getTotal() + "KB");
					// 文件系统剩余大小
					System.out.println(" Free = " + usage.getFree() + "KB");
					// 文件系统可用大小
					System.out.println(" Avail = " + usage.getAvail() + "KB");
					// 文件系统已经使用量
					System.out.println(" Used = " + usage.getUsed() + "KB");
					double usePercent = usage.getUsePercent() * 100D;
					// 文件系统资源的利用率
					System.out.println(" Usage = " + usePercent + "%");
					break;
				case 3:// TYPE_NETWORK ：网络
					break;
				case 4:// TYPE_RAM_DISK ：闪存
					break;
				case 5:// TYPE_CDROM ：光驱
					break;
				case 6:// TYPE_SWAP ：页面交换
					break;
				}
				System.out.println(" DiskReads = " + usage.getDiskReads());
				System.out.println(" DiskWrites = " + usage.getDiskWrites());
			}
			// 当前机器的正式域名
			try {
				hostname = InetAddress.getLocalHost().getCanonicalHostName();
			} catch (Exception e) {
				try {
					hostname = sigar.getFQDN();
				} catch (SigarException ex) {
					hostname = "unknown hostname.";
				}
			}
			// 取到当前机器的IP地址
			String address = null;
			try {
				address = InetAddress.getLocalHost().getHostAddress();
			} catch (Exception e) {
				try {
					address = sigar.getNetInterfaceConfig().getAddress();
				} catch (SigarException se) {
					address = NetFlags.LOOPBACK_ADDRESS;
				} finally {
					sigar.close();
				}
			}
			System.out.println(address);
			// 取到当前机器的MAC地址
			String mac = "";
			try {
				String[] ifaces = sigar.getNetInterfaceList();
				String hwaddr = null;
				for (int i = 0; i < ifaces.length; i++) {
					NetInterfaceConfig cfg = sigar.getNetInterfaceConfig(ifaces[i]);
					if (NetFlags.LOOPBACK_ADDRESS.equals(cfg.getAddress())
							|| (cfg.getFlags() & NetFlags.IFF_LOOPBACK) != 0
							|| NetFlags.NULL_HWADDR.equals(cfg.getHwaddr())) {
						continue;
					}
					/*
					 * 如果存在多张网卡包括虚拟机的网卡，默认只取第一张网卡的MAC地址，如果要返回所有的网卡（包括物理的和虚拟的）
					 * 则可以修改方法的返回类型为数组或Collection，通过在for循环里取到的多个MAC地址。
					 */
					hwaddr = cfg.getHwaddr();
					break;
				}
				mac = hwaddr != null ? hwaddr : null;
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println(mac);
			// 获取网络流量等信息
			String ifNames[] = sigar.getNetInterfaceList();
			for (int i = 0; i < ifNames.length; i++) {
				String name = ifNames[i];
				NetInterfaceConfig ifconfig = sigar.getNetInterfaceConfig(name);
				System.out.println("\nname = " + name);// 网络设备名
				System.out.println("Address = " + ifconfig.getAddress());// IP地址
				System.out.println("Netmask = " + ifconfig.getNetmask());// 子网掩码
				if ((ifconfig.getFlags() & 1L) <= 0L) {
					System.out.println("!IFF_UP...skipping getNetInterfaceStat");
					continue;
				}
				try {
					NetInterfaceStat ifstat = sigar.getNetInterfaceStat(name);
					System.out.println("RxPackets = " + ifstat.getRxPackets());// 接收的总包裹数
					System.out.println("TxPackets = " + ifstat.getTxPackets());// 发送的总包裹数
					System.out.println("RxBytes = " + ifstat.getRxBytes());// 接收到的总字节数
					System.out.println("TxBytes = " + ifstat.getTxBytes());// 发送的总字节数
					System.out.println("RxErrors = " + ifstat.getRxErrors());// 接收到的错误包数
					System.out.println("TxErrors = " + ifstat.getTxErrors());// 发送数据包时的错误数
					System.out.println("RxDropped = " + ifstat.getRxDropped());// 接收时丢弃的包数
					System.out.println("TxDropped = " + ifstat.getTxDropped());// 发送时丢弃的包数
				} catch (SigarNotImplementedException e) {
				} catch (SigarException e) {
					e.printStackTrace();
				}
			}
			// 一些其他的信息
			String[] ifaces = sigar.getNetInterfaceList();
			for (int i = 0; i < ifaces.length; i++) {
				NetInterfaceConfig cfg = sigar.getNetInterfaceConfig(ifaces[i]);
				if (NetFlags.LOOPBACK_ADDRESS.equals(cfg.getAddress()) || (cfg.getFlags() & NetFlags.IFF_LOOPBACK) != 0
						|| NetFlags.NULL_HWADDR.equals(cfg.getHwaddr())) {
					continue;
				}
				System.out.println("cfg.getAddress() = " + cfg.getAddress());// IP地址
				System.out.println("cfg.getBroadcast() = " + cfg.getBroadcast());// 网关广播地址
				System.out.println("cfg.getHwaddr() = " + cfg.getHwaddr());// 网卡MAC地址
				System.out.println("cfg.getNetmask() = " + cfg.getNetmask());// 子网掩码
				System.out.println("cfg.getDescription() = " + cfg.getDescription());// 网卡描述信息
				System.out.println("cfg.getType() = " + cfg.getType());//
				System.out.println("cfg.getDestination() = " + cfg.getDestination());
				System.out.println("cfg.getFlags() = " + cfg.getFlags());//
				System.out.println("cfg.getMetric() = " + cfg.getMetric());
				System.out.println("cfg.getMtu() = " + cfg.getMtu());
				System.out.println("cfg.getName() = " + cfg.getName());
				System.out.println();
			}
		} catch (SigarException e) {
			e.printStackTrace();
		} finally {
			sigar.close();
		}
	}

	private void printCpuPerc(CpuPerc cpu) {
		System.out.println("CPU用户使用率 :" + CpuPerc.format(cpu.getUser()));
		System.out.println("CPU系统使用率 :" + CpuPerc.format(cpu.getSys()));
		System.out.println("CPU当前等待率 :" + CpuPerc.format(cpu.getWait()));
		System.out.println("CPUNice :" + CpuPerc.format(cpu.getNice()));
		System.out.println("CPU当前空闲率 :" + CpuPerc.format(cpu.getIdle()));
		System.out.println("CPU总的使用率 :" + CpuPerc.format(cpu.getCombined()));
	}

	public static void main(String[] args) {
		Test t = new Test();
		t.getSystemInfo();
	}

}
